require 'fileutils'

class Wiki
  def initialize(article_root, archive_root)
    @Article_root = article_root
    @Archive_root = archive_root
  end

  # copy the article into the archive, and put a timestamp on it
  def archive(article)
    path = path(article)

    if File.exist?(path)
      if File.directory?(path)
        FileUtils.rmdir(path)
      else
        timestamp = Time.new.strftime('-%Y-%m-%d-%H:%M:%S')

        unless File.directory?(File.dirname(@Archive_root + article))
          FileUtils.mkdir_p(File.dirname(@Archive_root + article))
        end

        FileUtils.mv(path, @Archive_root + article + timestamp)
      end
    end
  end

  # return an array of files in the current directory
  def menu(article) 
    path = path(article)
    menu = []

    if File.directory?(File.dirname(path))
      path = File.dirname(path) unless File.directory?(path)

      Dir.entries(path).sort.each do |entry|
        next if entry =~ /^\./
        next if entry == 'index'
        if File.directory?(path + '/' + entry)
          entry << '/'
        end
        menu << entry
      end
    end

    return menu
  end

  # convert article to path
  def path(article)
    @Article_root + article
  end

  # return the article source
  def read(article)
    path = path(article)

    if File.exist?(path)
      return File.read(path)
    else
      return ''
    end
  end

  # save the article to a file
  def save(article, text)
    path = path(article)

    unless File.directory?(File.dirname(path))
      FileUtils.mkdir_p(File.dirname(path))
    end

    fout = File.open(path, 'w')
    fout.puts text.gsub(/\r\n/, "\n")
    fout.close
  end
end
